import "./index.scss";
import { Button, Checkbox, Form, Input, message } from "antd";
import { UserOutlined, UnlockOutlined } from "@ant-design/icons";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { loginAPI } from "@/apis/user";
import { setToken, setTefresh_token } from "@/store/modules/userStore";
import { useNavigate } from "react-router-dom";

function Login() {
	const navigate = useNavigate();
	// 获取信息 && 登录操作
	const dispatch = useDispatch();
	const [loading, setLoading] = useState();
	const [checked, setChecked] = useState(true);
	const onFinish = async formValue => {
		if (!checked) return message.error("请勾选条约");
		setLoading(true);
		setTimeout(async () => {
			const {
				data: { refresh_token, token },
			} = await loginAPI(formValue);
			setLoading(false);
			dispatch(setToken(token, "action"));
			dispatch(setTefresh_token(refresh_token));
			message.success("登录成功");
			navigate("/");
		}, 1000);
	};
	// mobile
	const rules = {
		mobile: [
			{ required: true, message: "请输入手机号" },
			{
				pattern: /^1[3-9]\d{9}$/,
				message: "手机号码格式不对",
			},
		],
		code: [{ required: true, message: "请输入验证码" }],
	};
	// checked
	const onChange = e => {
		setChecked(e.target.checked);
	};

	const [fields] = useState([
		{
			name: ["mobile"],
			value: "13888888888",
		},
		{
			name: ["code"],
			value: "246810",
		},
	]);
	return (
		<div className="login">
			<div className="login-form">
				<Form onFinish={onFinish} autoComplete="off" fields={fields}>
					<div className="form-title">学之思管理端</div>
					<Form.Item
						name="mobile"
						rules={rules.mobile}
						validateTrigger="onBlur"
					>
						<Input
							size="large"
							placeholder="请输入手机号"
							prefix={<UserOutlined />}
						/>
					</Form.Item>
					<Form.Item name="code" rules={rules.code} validateTrigger="onBlur">
						<Input
							size="large"
							placeholder="请输入验证码"
							prefix={<UnlockOutlined />}
						/>
					</Form.Item>
					<Form.Item name="checkbox" className="login-checkbox">
						<Checkbox checked={checked} onChange={onChange}>
							下次自动登录
						</Checkbox>
					</Form.Item>
					<Form.Item>
						<Button
							loading={loading}
							type="primary"
							size="large"
							htmlType="submit"
							block
						>
							登录
						</Button>
					</Form.Item>
				</Form>
			</div>
			<footer>
				<span>Copyright ©2020-2023 武汉思维跳跃科技有限公司 版权所有</span>
			</footer>
		</div>
	);
}
export default Login;
